package com.xiaoyu.lanling.util

import android.os.Build
import android.text.*
import android.text.method.LinkMovementMethod
import android.text.style.URLSpan
import android.view.View
import android.widget.TextView
import com.xiaoyu.base.model.User
import com.xiaoyu.base.utils.extensions.setViewTag
import com.xiaoyu.lanling.common.Constant
import com.xiaoyu.lanling.view.span.URLSpanNoUnderline

object TextViewUtil {
    fun displayOrGone(textView: TextView?, charSequence: CharSequence?, extra: Boolean = true) {
        if (!TextUtils.isEmpty(charSequence) && extra) {
            textView?.visibility = View.VISIBLE
            textView?.text = charSequence
        } else {
            textView?.visibility = View.GONE
        }
    }

    fun displayFor99PlusType(textView: TextView?, number: Int) {
        if (number > 0) {
            textView?.visibility = View.VISIBLE
            textView?.text = if (number > 99) "99+" else number.toString()
        } else {
            textView?.visibility = View.GONE
        }
    }

    fun displayFor999PlusType(textView: TextView, number: Int) {
        if (number > 0) {
            textView.visibility = View.VISIBLE
            textView.text = if (number > 999) "999+" else number.toString()
        } else {
            textView.visibility = View.GONE
        }
    }

    fun displayNicknameForUser(textView: TextView, user: User) {
        textView.text = user.remark
        textView.setViewTag(Constant.GlobalViewTagDefine.VIEW_TAG_FOR_UID, user.uid)
    }

    fun displayNicknameForUser(textView: TextView, nickname: CharSequence?, uid: String?) {
        textView.text = nickname
        textView.setViewTag(Constant.GlobalViewTagDefine.VIEW_TAG_FOR_UID, uid)
    }

    fun fromHtml(source: String?): Spanned {
        return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            Html.fromHtml(source, Html.FROM_HTML_MODE_LEGACY)
        } else {
            Html.fromHtml(source)
        }
    }

    fun setMovementMethod(textView: TextView) {
        textView.movementMethod = LinkMovementMethod.getInstance()
    }

    fun stripUnderlines(textView: TextView, text: String?) {
        val s: Spannable = SpannableString(fromHtml(text))
        val spans = s.getSpans(0, s.length, URLSpan::class.java)
        for (span in spans) {
            val start = s.getSpanStart(span)
            val end = s.getSpanEnd(span)
            s.removeSpan(span)
            s.setSpan(URLSpanNoUnderline(span.url), start, end, 0)
        }
        textView.text = s
    }

    fun stripUnderlinesAndClickable(textView: TextView, text: String?) {
        stripUnderlines(textView, text)
        setMovementMethod(textView)
    }
}